package com.loong.android.tools;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * DES加密解密
 */
public class Des {

    /**
     * 加密
     *
     * @param data 待加密的数据
     * @param key 秘钥字节数组
     * @param iv 初始化向量
     */
    public static byte[] encrypt(byte[] data, byte[] key, byte[] iv) {
        try {
            Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "DES"), new IvParameterSpec(iv));
            return cipher.doFinal(data);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 解密
     *
     * @param data 待解密的数据
     * @param key 秘钥字节数组
     * @param iv 初始化向量
     */
    public static byte[] decrypt(byte[] data, byte[] key, byte[] iv){
        try {
            Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, "DES"), new IvParameterSpec(iv));
            return cipher.doFinal(data);
        } catch (Exception e) {
            return null;
        }
    }
}
